package com.bw.home.view

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.bw.base.app.RoutePath
import com.bw.common.entity.SimpleVideoEntity
import com.bw.common.mvi.BaseMviFragment
import com.bw.home.R
import com.bw.home.adapter.HomeVideoListAdapter
import com.bw.home.databinding.FragmentHomeListBinding
import com.bw.home.intent.HomeViewIntent
import com.bw.home.state.HomeUiState
import com.bw.home.vm.HomeViewModel
import kotlinx.coroutines.launch
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import androidx.recyclerview.widget.SimpleItemAnimator


import com.bumptech.glide.Glide
import com.bw.cache.cache.RecyclerCachePool
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class HomeListFragment : BaseMviFragment<FragmentHomeListBinding>() {

    private val mViewModel: HomeViewModel by activityViewModels()

    private var typeId = 0
    private var channelId = ""
    private var pageIndex = 1
    private var pageSize = 10
    private var simpleVideoList = mutableListOf<SimpleVideoEntity>()
    private lateinit var videoListAdapter: HomeVideoListAdapter
    private var currentPosition = 0 // 当前显示的视频位置

    fun startVideoPlayback() {
        // 通知当前页面开始播放视频
        // 这里需要根据你的 RecyclerView 适配器实现来控制具体哪个视频播放
    }

    companion object{
        @JvmStatic
        fun newInstance(channelId: String, typeId: Int) = HomeListFragment().apply {
            arguments = Bundle().apply {
                putString("channelId", channelId)
                putInt("typeId", typeId)
            }
        }
    }

    override fun getLayoutId(): Int = R.layout.fragment_home_list

    override fun initViews() {
        //获取传递进来的参数
        arguments?.let {
            typeId = it.getInt("typeId")
            channelId = it.getString("channelId").toString()
        }

        //下来刷新事件
        mDataBinding.refreshLayout.setOnRefreshListener {
            if (simpleVideoList.size == 0 || pageIndex > 1){
                pageIndex = 1
                loadData()
            } else {
                mDataBinding.refreshLayout.finishRefresh()
            }
        }

        videoListAdapter = HomeVideoListAdapter(simpleVideoList).apply {
            //itemViewCache = HomeItemCache() //设置自定义缓存（可选）
            preloadEndCount = 4
            preloadMoreData = {
                pageIndex += 1
                loadData()
            }

            //添加点击事件
            setOnItemClickListener(object : HomeVideoListAdapter.OnItemClickListener{
                override fun onItemChick(v: View, position: Int) {
//                    when(v.id){
//                        R.id.iv_video_play -> {
//                            ARouter.getInstance().build(RoutePath.PATH_PLAY_PAGE)
//                                .withString("videoPath", simpleVideoList[position].videopath)
//                                .withString("userId", simpleVideoList[position].userid)
//                                .withInt("typeId", typeId)
//                                .withString("channelId", channelId)
//                                .withString("itemId", simpleVideoList[position].item_id)
//                                .withInt("moduleType", 0)
//                                .navigation()
//                        }
//                        R.id.iv_commend -> {
//                            //吐司
//                            ToastUtils.showShort("正在开发，敬请期待！")
//
//                        }
//                        R.id.iv_more-> {
//                            ToastUtils.showShort("正在开发，敬请期待！")
//                        }
//                    }
                }
            })

        }

        mDataBinding.rvVideoList.run {
            //设置屏幕外缓存ViewHolder的数量, 默认为2
            setItemViewCacheSize(12)
            //防止Item组件重复测量(适用于大小固定子组件)
            setHasFixedSize(true)
            //设置缓存池大小
            setRecycledViewPool(RecyclerCachePool)

            //添加滚动事件处理图片加载
            addOnScrollListener(object : OnScrollListener(){
                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    super.onScrollStateChanged(recyclerView, newState)
                    if (newState == RecyclerView.SCROLL_STATE_IDLE){ //滚动停止
                        //恢复图片加载
                        Glide.with(this@HomeListFragment).resumeRequests()
                    } else {
                        //暂停图片加载
                        Glide.with(this@HomeListFragment).pauseRequests()
                    }
                }
            })

            //关闭不必要的动画
            (itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false

            adapter = videoListAdapter
            layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        }



    }

    fun lazyLoadData(){
        //如果数据类型与传递进来的channelId不一致，需要清理掉后再加载
        if (simpleVideoList.size > 0 && simpleVideoList[0].channelid != channelId){
            simpleVideoList.clear()
            videoListAdapter.notifyDataSetChanged()
        }
        loadData()
    }


    private fun loadData(){
        lifecycleScope.launch {
            if (typeId == -1){
                mViewModel.channel.send(HomeViewIntent.LoadRecommendSimpleVideoList(pageIndex, pageSize))
            } else {
                mViewModel.channel.send(HomeViewIntent.LoadSimpleVideoList(channelId, pageIndex, pageSize))
            }
        }
    }

    override suspend fun collectUIState() {
        mViewModel.uiSharedFlow.collect{
            when(it){
                is HomeUiState.LoadSimpleVideoSuccess -> updatePageData(it.list)
                is HomeUiState.LoadSimpleVideoFail -> {
                    //回退到上一页
                    if (pageIndex > 1){
                        pageIndex -= 1
                    } else {
                        mDataBinding.refreshLayout.finishRefresh()
                        simpleVideoList.clear()
                        videoListAdapter.notifyDataSetChanged()
                    }
                }
                else -> {}
            }
        }
    }

    private fun updatePageData(list: List<SimpleVideoEntity>) {
        //如果下拉刷新获取第一页，需要清理
        if (pageIndex == 1){
            mDataBinding.refreshLayout.finishRefresh()
            simpleVideoList.clear()
        }
        simpleVideoList.addAll(list)
        videoListAdapter.notifyDataSetChanged()
    }


}











